$(function() {
    var cols=6;
	var rows_delete=0;
	var mode="add";
	var m_id=0; //student_id
	var pid=0; //product_id
	var m_term_id=0;
	var m_price=0;
	var m_payment_amt=0;
    var url='controls/pos_model.php';
	var list_input=[];
	initialData(); 
	 
	
	var checkDate = $('.btndate').datepicker().on('changeDate', function(ev) {
	  checkDate.hide();
	}).data('datepicker');
		
	$("#txtPayDate").val(_cdate);
	function initialData(){
	
		
		table_stock();
		
		$.get(url,{"m":"feetype"},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboFeeType").append(
						$('<option></option>').val(index).html(text)
					);
				});
			}
		});
		
		
		$("#cboClass_Search").append($('<option></option>').val(0).html(''));
		$.get(url, {"m":"class"},function(data){
			
			cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					
					$("#cboClass_Search").append(
							$('<option></option>').val(text).html(index)
					);
					 
				});
			
			//Load Room from Class (initial)
			LoadRoom(0);	 
			//Load Data Initail
			LoadStudent('','',1,0);
			}
		});
		
		LoadProductToTextBox();
		
		$("#txtProductCode").attr('disabled','disabled');
		$("#txtProduct").attr('disabled','disabled');
		$("#txtAmt").attr('disabled','disabled');
		$("#btnAddProduct").attr('disabled','disabled');
		$("#btnPaymentStock").attr('disabled','disabled');
		$("#btnAddList").attr('disabled','disabled');
		$("#btnPaymentTerm").attr('disabled','disabled');
		table_stock_history(0);
		
		table_term_payment(0);
		table_term_history(0);
	}
	
	$("#cboClass_Search").change(function(){
		var cid=$(this).val();
		
		$("#cboRoom_Search").find('option').remove();	
		
		$.get(url, {"m":"room","i":cid},function(data){
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboRoom_Search").append(
						$('<option></option>').val(text).html(index)
					);
				});
			}
		});
	});	
	
	//Search Student data
	$("#btnSearch").click(function(){
		var _code = $("#txtCode_S").val();
		var _name = $("#txtName_S").val();
		var _class= $("#cboClass_Search").val();
		var _room= $("#cboRoom_Search").val();
		
		LoadStudent(_code, _name, _class, _room);
		
	});
	
	$(".btnViweStudent").live('click',function(){
		var rows = $('#tb_student').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data = $('#tb_student').dataTable().fnGetData(rows);
		m_id = data[1];
	 
		$("#txtCode").val(data[2]);
		$("#txtName").val(data[3]);
		$("#txtClass").val(data[4]);
		$("#popup").modal('hide');
		
		$("#txtProductCode").removeAttr('disabled');
		$("#txtProduct").removeAttr('disabled');
		$("#txtAmt").removeAttr('disabled');
		$("#btnAddProduct").removeAttr('disabled');
		
		$("#btnAddList").removeAttr('disabled');
		
		table_term_payment(m_id);
		table_term_history(m_id);
		table_stock_history(m_id);
		
	});
	
	$("#txtCode").keypress(function(e){
		if (e.which==13){
			if ($("#txtCode").val() !=""){
				 $.ajax({
					 type: 'POST',
					 cache: false,
					 url: url,
					 data: {"m":"load_student_code","code":$("#txtCode").val()  },
					 success: function(data){
						if (data!='false'){
						var Obj=eval('('+data+')');	
						 
							$("#txtName").val(Obj['title_name'] +" " + Obj["thai_name"]+ " " + Obj['thai_surname']+" ("+Obj["thai_nickname"] +")");
							$("#txtClass").val(Obj['class_name']+'/'+Obj['room']);
							$("#popup").modal('hide');
							
							$("#txtProductCode").removeAttr('disabled');
							$("#txtProduct").removeAttr('disabled');
							$("#txtAmt").removeAttr('disabled');
							$("#btnAddProduct").removeAttr('disabled');
							
							$("#btnAddList").removeAttr('disabled');
						m_id=	Obj['student_id'];
						table_term_payment(Obj['student_id']); 
						table_term_history(Obj['student_id']);
						table_stock_history(Obj['student_id']);
					 }else{
						alert('ไม่พบข้อมูล');	
					 }
					 }
				 }); 
			}
		}
	});
	
	$("#btnAddProduct").click(function(){
		if (!($("#txtAmt").val() == "0" || $("#txtAmt").val()=="")){
			//m_price  	pid   //txtProduct
				$.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {'pid':pid,'m':'pd_id','amt': $("#txtAmt").val()},
					success: function(data){
					 
					var obj = eval('('+ data +')');
					 
					if (obj['result']!=1){
						 alert( obj['txt'] ); 
						 $("#txtProduct").val("");
						 $("#txtAmt").val("0");
						return false;						
					 }else{

						AddProduct(obj['val'],$("#txtAmt").val());
						$("#txtProduct").val("");
						$("#txtAmt").val("0");
						return true;
					 }
					}
				});
				return false;
		}
	});
	
	//Remove from Stock table
	$(".btnRemoveStock").live('click',function(){
		var rows = $(this).closest("tr").get(0);
        rows_delete = $('#tb_stock').dataTable().fnGetPosition(rows);
		var data =$('#tb_stock').dataTable().fnGetData(rows);
		 
		var _total = convertToNumber(data[6]);
		//remove array
		list_input.splice($.inArray(data[1], list_input),1);

		SumTotal("del", _total);
		
        $('#tb_stock').dataTable().fnDeleteRow(rows_delete);
        $('#tb_stock').dataTable().fnDraw();
	});
	// add new list
	$("#btnAddList").click(function(){
		$("#txtListAmount").val(0);
		$("#cboFeeType").val(1);
	
	});
	
	//Payment for Stock
	$("#btnPaymentStock").click(function(){
		mode='stock';
	});
	$("#btnPaymentTerm").click(function(){
		mode='term';
	});
	$("#btnSaveStock").click(function(){
		if (mode=='stock'){
		 var list = [];
			if ((list_input.length) > 0) {
				var rows = $('#tb_stock').dataTable().fnGetNodes();
				//Add 
				var student_id  =m_id;
				var total=0;
				var amt=0;
				for (var i = 0; i < rows.length; i++)
				{
					var row_data = $('#tb_stock').dataTable().fnGetData(rows[i]);
					
					list.push({'product_id': row_data[1],
						'amount':row_data[4],
						'price': row_data[5].replace(',','').replace(',','')
						});
					amt +=1;
					total +=  convertToNumber(row_data[6]);
				}
				
				$.ajax({
						type: 'POST',
						cache: false,
						url: url,
						data: {'m':'buyPd','list':list , 'id':m_id,'amt':amt,'total':total},
						success: function(data){
							//alert(data);
							$('#tb_stock').dataTable().fnClearTable();
							$("#txtTotalStockAmt").val(0);
							list_input=[];
							table_stock_history(m_id);
							$("#m_no").val(data);
							$("#frmSlip").get(0).setAttribute('action', 'rpt_slip_product.php');
			 
							$("#frmSlip").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
					
							$("#popupSave").modal('hide');
							
						}
					});
			}
		}else if (mode=='term'){
			$.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"pay_term_all","id":m_id },
				 success: function(data){
				 
					table_term_payment(m_id); 
					table_term_history(m_id);
					 
					
					$("#m_no").val(data);
					$("#frmSlip").get(0).setAttribute('action', 'rpt_pos.php');
			 
					$("#frmSlip").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');

					//$("#popup_payment").modal('hide');
					$("#m_term_id").val("");
					$("#popupSave").modal('hide');
					 
				 }
			 });
		}
		
	});
	
	
	$(".btnDel_term").live('click',function(){
		 
		var rows = $(this).closest("tr").get(0);
        rows_delete = $('#term_payment').dataTable().fnGetPosition(rows);
		var data =$('#term_payment').dataTable().fnGetData(rows);
		
		m_term_id = data[1];	
		
	});
	
	$(".btnPay_inputDate").live('click',function(){
		var rows = $(this).closest("tr").get(0);
        rows_delete = $('#term_payment').dataTable().fnGetPosition(rows);
		var data =$('#term_payment').dataTable().fnGetData(rows);
		m_term_id = data[1];	
		m_payment_amt=convertToNumber(data[5]);
	});
	$(".btnPay_term").live('click',function(){
		var rows = $(this).closest("tr").get(0);
        rows_delete = $('#term_payment').dataTable().fnGetPosition(rows);
		var data =$('#term_payment').dataTable().fnGetData(rows);
		
		m_term_id = data[1];	
		$("#payTitle").html(data[4]);
		$("#txtTerm_Remain_Amt").val(data[7]);
		$("#txtTerm_PayAmt").val(data[7]);
		
	});
	
	$(".btnPay_Course").live('click',function(){
		var rows = $(this).closest("tr").get(0);
        rows_delete = $('#term_payment').dataTable().fnGetPosition(rows);
		var data =$('#term_payment').dataTable().fnGetData(rows);
		m_term_id=data[1];
		$("#txtTotalCourse_PayAmt").val(data[7]);
		table_course(m_term_id);
	});
	
	$("input[name=txtCost]").live('keyup',function(event){
		var iTotal=0;
		if ( $(this).val()=='')
			$(this).val(0);
			
		$( "#tb_course_detail tbody tr").each(function(){
				//alert($(this).find("input[name=txtCost").eq(0).val());
				iTotal += convertToNumber($(this).find("input[name=txtCost]").eq(0).val());
		});
	//	alert(iTotal);
		$("#txtTotalCourse_PayAmt").val(CommaFormatted(iTotal.toFixed(2)));
	});
	
	$("#btnPayCourseConfirm").click(function(e){
		 
		if ( convertToNumber($("#txtTotalCourse_PayAmt").val()) > 0 ){
			$("#txtTotalCourse_PayAmt").removeAttr('style');
			var list = [];
			$( "#tb_course_detail tbody tr").each(function(){
			    var amt = $(this).find("input[name=txtCost]").val().replace(',',''); 
				var row_data = $('#tb_course_detail').dataTable().fnGetData(this);
				
				if (amt>0){
					  list.push({'id': row_data[1],
							'sid':row_data[2],
							'ctype':row_data[3],
                            'cost': amt  });
				}
			});
			//alert(list.length);
			if (list.length > 0){
				 $.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {"m": "update_course",  "list": list,"id":m_term_id },
					success: function(data) {
						table_term_payment(m_id); 
						table_term_history(m_id);
						
						$("#frmSlip").get(0).setAttribute('action', 'rpt_pos.php');
						$("#m_term_id").val(m_term_id);
						$("#frmSlip").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');

						//$("#popup_payment").modal('hide');
	 
						$("#popup_course").modal('hide');
					  
					}
				}); 
			}
		}else {
			$("#txtTotalCourse_PayAmt").attr('style', "background-color:#fddedb;border:1px solid #f99891");
		}
	});
	$("#btnSavePaymentDate").click(function(e){
		e.preventDefault(); 
		if ($("#txtPayDate").val() =="" ){
			return;
		}else{
			 var flag_close = 1;
			 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"pay_term_date","id":m_term_id , "pay_amount" : m_payment_amt , "pay_date" : $("#txtPayDate").val() , "isClose":flag_close },
				 success: function(data){
				 	table_term_payment(m_id); 
					table_term_history(m_id);
					$("#popup_payment_data").modal('hide');
				 }
			 }); 
				
		 
		}
	});
	$("#btnConfirmAddList").click(function(e){
		if ($("#txtListAmount").val() != "0"){
			$("#txtListAmount").removeAttr('style');
			
			 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"addlist","sid":m_id , "fee_id" : $("#cboFeeType").val(),"amt":$("#txtListAmount").val() },
				 success: function(data){
					if (data==0){
						table_term_payment(m_id); 
						$("#popup_Add_list").modal('hide');
					}else{
						alert("มีข้อมูลรายการอยู่แล้ว");
					}
				 }
			 }); 
				
		}else{
			$("#txtListAmount").focus();
			$("#txtListAmount").attr('style', "background-color:#fddedb;border:1px solid #f99891");
		}
	});
	$("#btnPayConfirm").click(function(e){
			e.preventDefault(); 
		if ($("#txtTerm_PayAmt").val() =="" || $("#txtTerm_PayAmt").val() =="0"){
			return;
		}else{
			var pay = convertToNumber($("#txtTerm_PayAmt").val());
			var remain = convertToNumber($("#txtTerm_Remain_Amt").val());
			
			if (pay>remain){
				 $("#txtTerm_PayAmt").attr('style', "background-color:#fddedb;border:1px solid #f99891");
				return;
			}else{
			 $("#txtTerm_PayAmt").removeAttr('style');	
			 var flag_close = (pay==remain?1:0);
	 
			 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"pay_term","id":m_term_id , "pay_amount" : pay , "isClose":flag_close },
				 success: function(data){
				 	table_term_payment(m_id); 
					table_term_history(m_id);
					
					
					$("#frmPaymentOther").get(0).setAttribute('action', 'rpt_pos.php');
					$("#slip_m_term_id").val(m_term_id);
					$("#frmPaymentOther").attr('target', '_blank').submit().removeAttr('target').removeAttr('action');
		
					$("#popup_payment").modal('hide');
					 
				 }
			 }); 
				
			}
		}
	});
	
	$(".btnViewStockDetail").live('click',function(){
		var rows = $(this).closest("tr").get(0);
        //rows_delete = $('#tb_payment_detail').dataTable().fnGetPosition(rows);
		var data =$('#stock_history').dataTable().fnGetData(rows);
		
		var s_id = data[1];	
		 //alert(s_id);
		
		load_stock_detail(s_id);
	});
	
	$(".btnpayment_detail").live('click', function(){
		var rows = $(this).closest("tr").get(0);
        //rows_delete = $('#tb_payment_detail').dataTable().fnGetPosition(rows);
		var data =$('#term_history').dataTable().fnGetData(rows);
		
		var code = data[3];	
		$("#slip_no").html("("+code+")");
		load_payment_detail(code);
		
	});
	
	$("#btnClosePaymentDetail").click(function(){
		$("#slip_no").html("");
		$("#tb_payment_detail").dataTable().fnClearTable();
	});
	//Popup confirm delete
	$("#btnDelete").live('click', function(){
		
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"del_term","id":m_term_id},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					 $('#term_payment').dataTable().fnDeleteRow(rows_delete);
					$('#term_payment').dataTable().fnDraw();
				 }
			 });
 
	}); 
	
	$(".txtamt").live('keypress',function(e) {

        if (e.which !== 8 && e.which !== 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }
    });
	
		
	$("#txtProductCode").keypress(function(e){
		if (e.which==13){
		 
			if ($(this).val()!=""){
				$.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {'code':$("#txtProductCode").val(),'m':'pd_code','amt':1},
					success: function(data){
					 
					var obj = eval('('+ data +')');
					 
					if (obj['result']!=1){
						 alert( obj['txt'] );// ('+obj['Amount'] + ' ' + obj['Unit']+')' );
						 $("#txtProductCode").val("");
						return false;						
					 }else{

						AddProduct(obj['val'],1);
						$("#txtProductCode").val("");
						return true;
					 }
					}
				});
				return false;	
			}
		
		}
	});
	
	function AddProduct(obj,amt){
 
		var index = ($.inArray( obj['id'], list_input ));
		if (index < 0){
			list_input.push(obj['id']);
			var total = new Number(parseInt(amt) * parseFloat(obj['price']));
			 
			$("#tb_stock").dataTable().fnAddData([
				0,  obj['id'] , obj['code'] , obj['name'] , amt , obj['price'] , CommaFormatted(total.toFixed(2))
			]);
			
			 
		}else{
		    var o_amt=  $("#tb_stock").dataTable().fnGetData(index,4);
			var n_amt = parseInt(o_amt) + parseInt(amt);
			var total = new Number(parseInt(n_amt) * parseFloat(obj['price']));
			$("#tb_stock").dataTable().fnUpdate( n_amt , index, 4);
			$("#tb_stock").dataTable().fnUpdate( CommaFormatted(total.toFixed(2)) , index, 6);
		}
		
		var t = new Number(parseInt(amt) * parseFloat(obj['price']));
		
		SumTotal("add", t);
		
	}
	
	function SumTotal(type,total){
		var grand_total = new Number($("#txtTotalStockAmt").val().replace(',','').replace(',',''));
		if(type=="add"){
			$("#txtTotalStockAmt").val(CommaFormatted( (total + grand_total).toFixed(2) ));
		}else{
			$("#txtTotalStockAmt").val(CommaFormatted( (grand_total - total).toFixed(2) ));
		}
	}
	 function table_course(id){
		$("#tb_course_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
			"bAutoWidth": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_course_by_student"},
							{"name":"id","value":id}      
				);
            },
            "aoColumnDefs": [
				{"bVisible": false, "aTargets": [1], "sClass": "center"}, //id,
				{"bVisible": false, "aTargets": [2], "sClass": "center"}, // student-id
				{"bVisible": false, "aTargets": [3], "sClass": "center"}, // course type 
                {"bSortable": true, "aTargets": [4], "sClass": "text-left"}, // course name
                {"bSortable": true, "aTargets": [5], "sClass": "text-right"}, //cost
				{"bSortable": true, "aTargets": [6], "sClass": "center"} //cost 2
 
            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });
	}
	function table_stock_history(id){
		$("#stock_history").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": true,
			"bAutoWidth": false,
            "bPaginate": true,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_st_histy"},
							{"name":"id","value":id}      
				);
            },
            "aoColumnDefs": [
				{"bVisible": false, "aTargets": [1], "sClass": "center"},
                {"bSortable": true, "aTargets": [2], "sClass": "center"}, //code
                {"bSortable": true, "aTargets": [3], "sClass": "center"}, // date
                {"bSortable": true, "aTargets": [4], "sClass": "text-center"}, //year
				{"bSortable": true, "aTargets": [5], "sClass": "center"}, //term
				{"bSortable": true, "aTargets": [6], "sClass": "center"}, // amt
				{"bSortable": true, "aTargets": [7], "sClass": "center"}, // total
				{"bSortable": true, "aTargets": [8], "sClass": "text-left"}, //name
				{"aTargets": [9],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                       
                            return "<a href='#popup_stock_detail' data-toggle='modal' ><img src='img/doc.png' width='24px' class='btnViewStockDetail' style='cursor:pointer;'/></a>";
                       
                    }
                }
				/*,
                {"aTargets": [10],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                       
                            return "<a href='#'  ><img src='img/print2.png' width='24px' class='btnPrintStock' style='cursor:pointer;'/></a>";
                       
                    }
                }*/

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });
	}
	
	function table_stock(){
	$("#tb_stock").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
			"bAutoWidth": false,
            "bPaginate": false,
            "bLengthChange": false,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
			  "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1], "sClass": "center"},
				{"bSortable": true, "aTargets": [2], "sClass": "text-center"}, //code
                {"bSortable": true, "aTargets": [3], "sClass": "text-left"}, // name 
                {"bSortable": true, "aTargets": [4], "sClass": "text-right"}, //amt
				{"bSortable": true, "aTargets": [5], "sClass": "text-right"}, // price
				{"bSortable": true, "aTargets": [6], "sClass": "text-right"}, //total
                {"aTargets": [7],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                            return "<a href='#'  ><img src='img/delete.png' width='24px' class='btnRemoveStock' style='cursor:pointer;'/></a>";
                       
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
					$("#btnPaymentStock").removeAttr('disabled');
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }else{
					$("#btnPaymentStock").attr('disabled','disabled');
				}

            }

        });
    }
    
	function CommaFormatted(amount){
		 
			var delimiter = ","; // replace comma if desired
			var a = amount.split('.',2)
			var d = a[1];
			var i = parseInt(a[0]);
			if(isNaN(i)) { return ''; }
			var minus = '';
			if(i < 0) { minus = '-'; }
			i = Math.abs(i);
			var n = new String(i);
			var a = [];
			while(n.length > 3)
			{
				var nn = n.substr(n.length-3);
				a.unshift(nn);
				n = n.substr(0,n.length-3);
			}
			if(n.length > 0) { a.unshift(n); }
			n = a.join(delimiter);
			if(d.length < 1) { amount = n; }
			else { amount = n + '.' + d; }
			amount = minus + amount;
			return amount;
	}
	
	function table_term_payment(id){
	
	    var _totalRemain = 0;
		$("#term_payment").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
			"bAutoWidth": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_pay_term"},
							{"name":"id","value":id}     
				);
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1], "sClass": "center"}, //id
                {"bSortable": true, "aTargets": [2], "sClass": "text-center"}, // year
                {"bSortable": true, "aTargets": [3], "sClass": "text-center"}, //term
				{"bSortable": true, "aTargets": [4], "sClass": "text-left"}, //type
				{"bSortable": true, "aTargets": [5], "sClass": "text-right"}, // amt
				{"bSortable": true, "aTargets": [6], "sClass": "text-right"}, // pay
				{"bSortable": true, "aTargets": [7], "sClass": "text-right"}, // remain
				{"bVisible": false, "aTargets": [8], "sClass": "text-right"}, // type
                {"aTargets": [9],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
							if (full[8]==6){
								//Course
								return "<a href='#popup_course' data-toggle='modal' ><img src='img/creditsale_icon.png' width='24px' class='btnPay_Course' style='cursor:pointer;'/></a>";
								//return "<a href='#popup_payment' data-toggle='modal' ><img src='img/creditsale_icon.png' width='24px' class='btnPay_term' style='cursor:pointer;'/></a>";
							}else if (full[8]==1){
								// Payment Term
								return "<a href='#popup_payment_data' data-toggle='modal' ><img src='img/check_product.png' width='24px' class='btnPay_inputDate' style='cursor:pointer;'/></a>";
							}else {
								return "<a href='#popup_payment' data-toggle='modal' ><img src='img/creditsale_icon.png' width='24px' class='btnPay_term' style='cursor:pointer;'/></a>";
							}
                            
                    }
                },
				 
				{"aTargets": [10],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
						if (_te ==1)
                            return "<a href='#popupConfirm' data-toggle='modal' ><img src='img/delete-file.png' width='24px' class='btnDel_term' style='cursor:pointer;'/></a>";
						else 
							return "";
                    }
                }


            ],  "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				var amtTotal=0;
                if (iTotalRecords > 0) {
					$("#btnPaymentTerm").removeAttr('disabled');
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
					
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
							amtTotal += convertToNumber(oSettings.aoData[ oSettings.aiDisplay[i] ]._aData[7]);
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
						$("#txtRemailTotal").val(CommaFormatted(amtTotal.toFixed(2)));
                    }
                }else{
					$("#btnPaymentTerm").attr('disabled','disabled');
				}

            }

        });
		
	}
	function table_term_history(id){
		$("#term_history").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": true,
			"bAutoWidth": false,
            "bPaginate": true,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
           "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_pay_history"},
							{"name":"id","value":id}     
				);
            },
            "aoColumnDefs": [
                {"bSortable": true, "aTargets": [1], "sClass": "text-center"}, //year
                {"bSortable": true, "aTargets": [2], "sClass": "text-center"}, // term
                {"bSortable": true, "aTargets": [3], "sClass": "text-center"}, //code
				{"bSortable": true, "aTargets": [4], "sClass": "text-center"}, //date
				{"bSortable": true, "aTargets": [5], "sClass": "text-left"}, // amount
				{"bSortable": true, "aTargets": [6], "sClass": "text-right"}, // name
				{"aTargets": [7],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                            return "<a href='#popup_payment_detail' data-toggle='modal' ><img src='img/doc.png' width='24px' class='btnpayment_detail' style='cursor:pointer;'/></a>";
                    }
                }
 

            ],
            
             "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });
	
	}
	function load_payment_detail(m_code){
	$("#tb_payment_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
			"bAutoWidth": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_payment_detail"},
							{"name":"code","value":m_code}
				);
            },
            "aoColumnDefs": [
                {"bSortable": true, "aTargets": [1], "sClass": "text-left"},
                {"bSortable": true, "aTargets": [2], "sClass": "text-right"} 
                  
            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });
	}
  
  function load_stock_detail(id){
	$("#tb_stock_history_detail").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": false,
			"bAutoWidth": false,
            "bPaginate": false,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_stock_history_detail"},
							{"name":"id","value":id}
				);
            },
            "aoColumnDefs": [
                {"bSortable": true, "aTargets": [1], "sClass": "text-center"},
				{"bSortable": true, "aTargets": [2], "sClass": "text-left"},
				{"bSortable": true, "aTargets": [3], "sClass": "text-right"},
                {"bSortable": true, "aTargets": [4], "sClass": "text-right"} 
                  
            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });
	}
	
    function LoadRoom(cid){
	 	$.get(url, {"m":"room","i":cid},function(data){
 
			var cboObj=eval('('+data+')');	
			if (cboObj != null){
				$.each(cboObj, function(index, text) {
					$("#cboRoom_Search").append(
						$('<option></option>').val(text).html(index)
					);
				});
			}
		});
	 }
  
   function LoadStudent(code,name,_class,room){
		$("#tb_student").dataTable({"bProcessing": true,
            "bFilter": false,
            "bInfo": true,
            "bPaginate": true,
            "bLengthChange": false,
            "sAjaxSource": url,
            "oLanguage": {
                "sEmptyTable": "ไม่พบข้อมูล"
            },
            "bDestroy": true,
            "sServerMethod": "POST",
            "fnServerParams": function(aoData) {
                aoData.push({"name": "m", "value": "load_student"},
							{"name":"classid","value":_class},
							{"name":"room","value":room},
							{"name":"code","value":code},
							{"name":"name","value":name}      
				);
            },
            "aoColumnDefs": [
                {"bVisible": false, "aTargets": [1], "sClass": "center"},
                {"bSortable": true, "aTargets": [2], "sClass": "center"},
                {"bSortable": true, "aTargets": [3], "sClass": "text-left"},
				{"bSortable": true, "aTargets": [4], "sClass": "center"},
                {"aTargets": [5],
                    "sClass": "center",
                    "mData": null,
                    "mRender": function(data, type, full) {
                       
                            return "<a href='#'  ><img src='img/folder_add_32.png' width='24px' class='btnViweStudent' style='cursor:pointer;'/></a>";
                       
                    }
                }

            ], "fnDrawCallback": function(oSettings) {
                var that = this;
                /* Need to redo the counters if filtered or sorted */
                var iTotalRecords = oSettings.fnRecordsTotal();
                //alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);

                if (iTotalRecords > 0) {
                    if (oSettings.bSorted || oSettings.bFiltered)
                    {
                        for (var i = 0, iLen = iTotalRecords; i < iLen; i++)
                        {
                            $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr).html(i + 1);
                        }
                    }
                }

            }

        });
   }
   function convertToNumber(num){
		var value=0;
		num = num.replace(',','').replace(',','');
		if (!(isNaN(num))){
			value= parseFloat( num , 10);
		}
		return value;
	}
    function LoadProductToTextBox(){
    //Clear data
		$('#txtProduct').off();
		$('#txtProduct').data('typeahead', (data = null));

			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m": "getProduct", "t": 3},
				success: function(data) {
					var sourceArr = [];
					var jsonObj = $.parseJSON(data);

					$('#txtProduct').typeahead({
						source: function(query, process) {
							objects = [];
							map = {};
							var data = jsonObj; // Or get your JSON dynamically and load it into this variable
							$.each(data, function(i, object) {
								map[object.label] = object;
								objects.push(object.label);
							});
							process(objects);
						},
						updater: function(item) {
							// $('hiddenInputElement').val(map[item].id);
							pid = map[item].id;
							m_price =  map[item].price;
							return item;
						}
					});
				}
			});
	}
 
    //initial get product 
    if ($("#txtProduct")[0]) {
        LoadProductToTextBox();
    }
    
});

(function( $ ) {
		$.widget( "ui.combobox", {
		_create: function() {
				var self = this,
					select = this.element.hide(),
					selected = select.children( ":selected" ),
					value = selected.val() ? selected.text() : "";
				var input = this.input = $( "<input>" )
					.insertAfter( select )
					.val( value )
					.autocomplete({
						delay: 0,
						minLength: 0,
						source: function( request, response ) {
							var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
							response( select.children( "option" ).map(function() {
								var text = $( this ).text();
								if ( this.value && ( !request.term || matcher.test(text) ) )
									return {
										label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "<strong>$1</strong>" ),
										value: text,
										option: this
									};
							}) );
						},
						select: function( event, ui ) {
							ui.item.option.selected = true;
							self._trigger( "selected", event, {
								item: ui.item.option
							});
						},
						change: function( event, ui ) {
							if ( !ui.item ) {
								
								var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
									valid = false;
									select.children( "option" ).each(function() {
									if ( $( this ).text().match( matcher ) ) {
										this.selected = valid = true;
										return false;
									}
								});
								if ( !valid ) {
									// remove invalid value, as it didn't match anything
									$( this ).val( "" );
									select.val( "" );
									input.data( "autocomplete" ).term = "";
									return false;
								}
							}
						}
					})
					.addClass( "ui-widget ui-widget-content ui-corner-left" );
					
					input.data( "autocomplete" )._renderItem = function( ul, item ) {
					return $( "<li></li>" )
						.data( "item.autocomplete", item )
						.append( "<a>" + item.label + "</a>" )
						.appendTo( ul );
				};

				this.button = $( "<button type='button'>&nbsp;</button>" )
					.attr( "tabIndex", -1 )
					.attr( "title", "Show All Items" )
					.insertAfter( input )
					.button({
						icons: {
							primary: "ui-icon-triangle-1-s"
						},
						text: false
					})
					.removeClass( "ui-corner-all" )
					.addClass( "ui-corner-right ui-button-icon" )
					.click(function() {
						// close if already visible
						if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
							input.autocomplete( "close" );
							return;
						}

						// pass empty string as value to search for, displaying all results
						input.autocomplete( "search", "" );
						input.focus();
					});
			}
		});
})( jQuery );

